<?php
class MY_Controller extends CI_Controller
{
	protected $controller_name;
    protected $action_name;
	
	function __construct()
	{
		parent::__construct();
		
		$this->load_defaults();
	}
		
	
	protected function load_defaults() {
		// Refresh Session
		$this->session_refresh();
		
		// Set Route
		$this->controller_name = $this->router->fetch_directory() . $this->router->fetch_class();
        $this->action_name = $this->router->fetch_method();
		
		$this->data	= (array_key_exists('data', $_POST) ? $_POST['data'] : NULL);
		$this->data['controller_name'] = $this->controller_name;
		$this->data['action_name'] = $this->action_name;
		
		$current_app	= $this->get_data("SELECT APP_ID FROM IT_SESSION WHERE SESSID = '"._SESSID."'");
		if($current_app == '') $current_app = 'CORE';
		define('APP', $current_app);
		$current_site	= $this->config->item('current_site');
		define('CURRENT_SITE', $current_site);
		//@parse_str($_SERVER['QUERY_STRING'],$_GET);
		
		// Set Template
		global $template,$default_title;
		$template = $this->web_option('CURRENT_THEME');
		
		
		// Set Session Menu Id
		if(post('session_menu_id')!=''){
			$session_menu_id	= post('session_menu_id');
			$session_menu_label	= $this->get_data("SELECT MENU_LABEL FROM IT_MENU WHERE MENU_ID = '".$session_menu_id."'");
			$this->session->set_userdata('session_menu_id', $session_menu_id);
			$this->session->set_userdata('session_menu_label', $session_menu_label);
		}
		
		// Get Session Menu Id & Label
		$sess_data	= $this->session->all_userdata();
		if(is_array($sess_data) && array_key_exists('session_menu_id',$sess_data) ){
			$this->session_menu_id		= $sess_data['session_menu_id'];
		}else{
			$this->session_menu_id		= '';
		}
		if(is_array($sess_data) && array_key_exists('session_menu_label',$sess_data) ){
			$this->session_menu_label	= $sess_data['session_menu_label'];
		}else{
			$this->session_menu_label	= '';
		}
		
		
		// Load Model
		$this->load->model('app_model', 'App');
		
		
	}
	
	function get_data($sql_string){
		$result = $this->db->query($sql_string);
		$arr_data = $result->result_array();
		
		if(count($arr_data)==0){
			return '';
		}else{
			$row		= $arr_data[0];
			$array_key	= array_keys($row);
			
			if(count($array_key)==0){
				return '';
			}else{
				$key	= $array_key[0];
				return $row[$key];
			}
		}
	}
	
	function protect_referer(){
		if(@strstr(	str_replace('http://www.','http://',strtolower($_SERVER['HTTP_REFERER'])),
					str_replace('http://www.','http://',base_url())) == ''){
			
			if(file_exists(APPPATH . 'errors/error_directaccess.php')){
				include(APPPATH . 'errors/error_directaccess.php');
			}else{
				echo 'Direct Access is not allowed'; 
			}
			
			die;
		}
	}
	
	function web_option($option_name='', $option_value=''){
		if(trim($option_value)!=''){
			$this->db->update(	'IT_CONFIG', 
								array(	'CONFIG_VALUE'	=> (is_array($option_value) ? json_encode($option_value) : $option_value)), 
								array(	'APP_ID'		=> (defined('CURRENT_APP') && CURRENT_APP != ''  ? CURRENT_APP : 'CORE'), 
										'CONFIG_NAME'	=> $option_name)); 
		} else {
			$value	= $this->get_data("SELECT CONFIG_VALUE FROM IT_CONFIG WHERE APP_ID = '".(defined('CURRENT_APP') && CURRENT_APP != ''  ? CURRENT_APP : 'CORE')."' AND CONFIG_NAME = '".$option_name."'");
			if(@strstr($value,'[')!='' || @strstr($value,'{')!=''){ $value = json_decode($value); }
			return $value;
		}
	}
	
	
	// Special Helper Function
	function MessageTemplate($code)
	{
		$this->db->select('*');
		$this->db->from('IT_SYSTEM_MESSAGE');
		$this->db->where('CODE', $code);
		
		$result = $this->db->get();
		
		if($result->num_rows()==1){
			$arr_data	= $result->row_array();
			return $arr_data;
		}else{
			return NULL;
		}
	}
	
	function PostResponse($input)
	{
		$form_sender = post("form_sender");
		$useupload = (intval(post("useupload")) == 1);
		if ($useupload) { return '<script type="text/javascript">parent.afterSubmit = parent.$_id(\''.$form_sender.'\').data(\'afterSubmit\'); var lb_submit = parent.afterSubmit('.$input.'); if(lb_submit){ var lf_onComplete = parent.$_id(\''.$form_sender.'\').data(\'onComplete\'); lf_onComplete(); }else{ var lf_onError = parent.$_id(\''.$form_sender.'\').data(\'onError\'); lf_onError(); } parent.setLoading(false);</script>'; }else{ return $input; }
	}
	
	// --------------------------------------------------------------------
	/**
	 * Session Collection 
	 *
	 * @access	public
	 */	
	function session_refresh(){
		$sessid 				= md5(client_ip() . NOW );
		$time_adjust 			= $this->config->item('time_adjust');
		$ls_session_expired		= $this->web_option("SESSION_EXPIRED");
		$SESSION_EXPIRED		= ($ls_session_expired == "" ? 30 : intval($ls_session_expired));
		$time_adjust			= $this->config->item('time_adjust');
		
		if(isset($this->db)){
			$this->db->where("SESSION_EXPIRE < TO_DATE('".@date("Y-m-d H:i:s", strtotime($time_adjust))."','YYYY-MM-DD HH24:MI:SS')");
			$this->db->delete('IT_SESSION');
			 
			$sess_data	= $this->session->all_userdata();
			$sessid		= '';
			if(is_array($sess_data) && array_key_exists('arr_session',$sess_data) && 
			is_array($sess_data['arr_session']) && array_key_exists('sessid',$sess_data['arr_session'])){
				$sessid 			= $sess_data['arr_session']['sessid'];
				$this->db->update(	'IT_SESSION', 
									array('SESSION_EXPIRE' => @date("Y-m-d H:i:s", strtotime($time_adjust." +".$SESSION_EXPIRED." minutes"))), 
									array('SESSID' => $sessid));
			}
			if(!defined('_SESSID')) define('_SESSID',$sessid);
		}else{
			$sess_data	= $this->session->all_userdata();
			$sessid		= '';
			if(is_array($sess_data) && array_key_exists('arr_session',$sess_data) && 
			is_array($sess_data['arr_session']) && array_key_exists('sessid',$sess_data['arr_session'])){
				$sessid	= $sess_data['arr_session']['sessid'];
			}
			if(!defined('_SESSID')) define('_SESSID',$sessid);
		}
	}
	
	function session_read($sessid = ''){
		if($sessid=='') $sessid = _SESSID; 
		if($sessid!=''){
			if(isset($this->db)){
				/*$this->db->select('*');
				$this->db->from('it_session');
				$this->db->join('it_user', 'it_session.owner=it_user.user_id');
				$this->db->where('sessid', $sessid);*/
				
				$result = $this->db->query("SELECT  * 
                                            FROM    IT_SESSION A
                                                    JOIN IT_USERID B ON A.OWNER=B.USER_ID
                                                    LEFT JOIN IT_MENU_ACCESS C ON A.ROLE_ID = C.ROLE_ID AND MENU_ID='".$this->session_menu_id."'
                                            WHERE    SESSID = '".$sessid."'");
				
				if($result->num_rows()==1){
					$arr_data	= $result->row_array();
					
					if(!defined('USERID')) define('USERID', $arr_data['user_id']);
					if(!defined('ROLE')) define('ROLE', $arr_data['role_id']);
					if(!defined('CULTURE')) define('CULTURE', 'id');
					
					if(!defined('PERMISSION_C')) define('PERMISSION_C', $arr_data['cr']);
					if(!defined('PERMISSION_R')) define('PERMISSION_R', 'Y');
					if(!defined('PERMISSION_U')) define('PERMISSION_U', $arr_data['up']);
					if(!defined('PERMISSION_D')) define('PERMISSION_D', $arr_data['dl']);
					if(!defined('PERMISSION_PR')) define('PERMISSION_PR', $arr_data['pr']);
					if(!defined('PERMISSION_DW')) define('PERMISSION_DW', $arr_data['dw']);
					if(!defined('PERMISSION_UP')) define('PERMISSION_UP', $arr_data['upl']);
					
					return $arr_data;
				}else{
					return NULL;
				}
			}else
			{
				$sess_data	= $this->session->all_userdata();
				if(is_array($sess_data) && array_key_exists('arr_session',$sess_data) && 
				is_array($sess_data['arr_session']) && array_key_exists('sessid',$sess_data['arr_session'])){
					return $sess_data['arr_session'];
				}else{
					return NULL;
				}
			}
		}
		return NULL;
	}
	
	function secure_session(){
		$arr_session	= $this->session_read();
		if($arr_session==NULL){ if(defined('IS_AJAX') && IS_AJAX){ echo 'Session Expired'; }else{ redirect(base_url()); } die; }
	}
} 
?>